import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:wallpaper_client_plugin/model/CateItem.dart';
import 'package:wallpaper_client_plugin/model/DownloadResult.dart';
import 'package:wallpaper_client_plugin/wallpaper_client_plugin.dart';
import 'package:wallpaper_client_plugin_example/catalog.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  bool _sensorsAvailable = false;
  final _wallpaperClientPlugin = WallpaperClientPlugin();
  List<CatelogItem> _catelogItemList = List.empty();
  final Map<String, Completer> mapCompleter = {};
  final MethodChannel channel = const MethodChannel('wallpaper_client_plugin');

  @override
  void initState() {
    super.initState();
    initPlatformState();

    getCatelogItemList();

    channel.setMethodCallHandler((MethodCall call) async {
      var result = DownloadResult()..fromJson(call.arguments as Map);
      if (call.method == 'downloadWallpaperCompleted') {
        // 下载成功
        mapCompleter[result.id]?.complete();
      } else if (call.method == 'downloadWallpaperFailed') {
        // 下载失败
         mapCompleter[result.id]?.completeError(Exception("下载失败"));
      } else if(call.method == 'downloadWallpaperProgress') {
        // 下载进度
        print('下载进度:'+result.percent.toString() + ',已下载:'+result.downloadedBytes.toString() + ',文件大小:'+result.totalBytes.toString());
      }
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    bool sensorsAvailable = false;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _wallpaperClientPlugin.getPlatformVersion() ?? 'Unknown platform version';
      sensorsAvailable = await _wallpaperClientPlugin.sensorsAvailable() ?? false;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
      _sensorsAvailable = sensorsAvailable;
    });
  }


  Future<void> getCatelogItemList() async {
    setState(() {
      _catelogItemList = catelog.map((item) => CatelogItem()..fromJson(item)).toList();
    });
  }

Future downloadAsync(CatelogItem item) {
  var completer = Completer();
   _wallpaperClientPlugin.downloadWallpaper(item);
  mapCompleter[item.id.toString()] = completer;
  return completer.future;
}

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "壁纸应用",
      theme: ThemeData.dark(useMaterial3: true),
      home: Scaffold(
        primary: false,
        appBar: AppBar(
          title: const Text('壁纸应用', style: TextStyle(fontSize: 16),),
        ),
        body: CustomScrollView(
          slivers: [
            SliverGrid.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 3,
                mainAxisSpacing: 3
              ), 
              itemBuilder: (context, index) => 
              GestureDetector(
                child: Container(
                  child: Image.network(
                    _catelogItemList[index].getThumbnail(),
                    fit: BoxFit.contain,
                  )
                ),
                onTap: () {
                  // 应用壁纸
                  showModalBottomSheet(
                      context: context,
                      backgroundColor: Colors.transparent,
                      builder: (context) {
                        return Column(
                          children: [
                            FilledButton(onPressed: () {
                              _wallpaperClientPlugin.downloadWallpaper(_catelogItemList[index]);
                            }, child: Text("下载壁纸")),
                            FilledButton(onPressed: () {
                              _wallpaperClientPlugin.setWallpaper(_catelogItemList[index]);
                            }, child: Text("设置壁纸")),
                            FilledButton(onPressed: () async {
                              var item = _catelogItemList[index];
                              try {
                                 await downloadAsync(item);
                                  _wallpaperClientPlugin.setWallpaper(item);
                              } catch (e) {
                                print(e); 
                              }
                            }, child: Text("下载并设置壁纸"))
                          ],
                        );
                  });
                },
              ),
              itemCount: _catelogItemList.length,
            )
          ],
        )
      ),
    );
  }
}
